/**
 * 日志工具模块
 */
const fs = require('fs');
const path = require('path');

// 创建日志目录
const logDir = path.join(__dirname, '../logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 获取当前日期字符串
function getDateString() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
}

// 获取当前时间字符串
function getTimeString() {
  const now = new Date();
  return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}.${String(now.getMilliseconds()).padStart(3, '0')}`;
}

// 日志级别
const LogLevel = {
  DEBUG: 'DEBUG',
  INFO: 'INFO',
  WARN: 'WARN',
  ERROR: 'ERROR'
};

/**
 * 写日志到文件
 * @param {string} level 日志级别
 * @param {string} message 日志消息
 * @param {object} data 附加数据
 */
function log(level, message, data = null) {
  const dateStr = getDateString();
  const timeStr = getTimeString();
  const logFile = path.join(logDir, `app-${dateStr}.log`);
  
  let logMessage = `[${timeStr}] [${level}] ${message}`;
  
  // 如果有附加数据，格式化为字符串
  if (data) {
    let dataStr;
    try {
      dataStr = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
    } catch (e) {
      dataStr = '[无法序列化的数据]';
    }
    logMessage += `\n${dataStr}`;
  }
  
  // 打印到控制台
  switch (level) {
    case LogLevel.ERROR:
      console.error(logMessage);
      break;
    case LogLevel.WARN:
      console.warn(logMessage);
      break;
    case LogLevel.INFO:
      console.info(logMessage);
      break;
    default:
      console.log(logMessage);
  }
  
  // 写入日志文件
  fs.appendFileSync(logFile, logMessage + '\n\n');
}

module.exports = {
  debug: (message, data) => log(LogLevel.DEBUG, message, data),
  info: (message, data) => log(LogLevel.INFO, message, data),
  warn: (message, data) => log(LogLevel.WARN, message, data),
  error: (message, data) => log(LogLevel.ERROR, message, data),
  LogLevel
};
